//
//  ILGAnimationView.m
//  WangHuo
//
//  Created by zhangtongle-Pro on 2017/7/10.
//  Copyright © 2017年 ifeng. All rights reserved.
//

#import "ILGAnimationView.h"

@interface ILGAnimationView ()
@property (nonatomic, strong) UIButton *coverBtn;
@end

@implementation ILGAnimationView

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)dealloc {
    NSLog(@"视图已被释放:%@",NSStringFromClass([self class]));
}

- (void)setFrame:(CGRect)frame {
    CGRect tmpFrame = frame;
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeAreaInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
        tmpFrame.size.height += safeAreaInsets.bottom;
    }
    [super setFrame:tmpFrame];
}

- (UIButton *)coverBtn {
    if (!_coverBtn) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.1];
        [btn addTarget:self action:@selector(hideFromBottom) forControlEvents:UIControlEventTouchUpInside];
        _coverBtn = btn;
    }
    return _coverBtn;
}


#pragma mark - public method

+ (instancetype)view {
    return [[self alloc] init];
}

+ (instancetype)viewFromXIB {
    return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil].firstObject;
}

- (void)showFromBottom {
    [self showFromBottomWithExtraHeight:0];
}

- (void)showFromBottomWithExtraHeight:(CGFloat)extraHeight {
    [self.coverBtn setFrame:self.superview.bounds];
    [self.superview insertSubview:self.coverBtn belowSubview:self];
    
    //动画
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.transform = CGAffineTransformMakeTranslation(0, -(weakSelf.bounds.size.height+extraHeight));
    }];
}

- (void)hideFromBottom:(BOOL)animated {
    CGFloat duration = 0.25;
    if (!animated) {
        duration = 0.0;
    }
    
    //动画
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:duration animations:^{
        weakSelf.transform = CGAffineTransformIdentity;
    }completion:^(BOOL finished) {
        [weakSelf.coverBtn removeFromSuperview];
    }];
}

- (void)hideFromBottom {
    [self hideFromBottom:YES];
}

@end
